<template>
	<div class="container">
		<cl-crud @load="onLoad">
			<template #slot-add="{scope}">
				<el-button
					size="mini"
					type="primary"
					@click="addRecord()"
					v-permission="$service.coupon.record.permission.add"
				>
					<i class="el-icon-plus"></i>添加记录
				</el-button>
			</template>
			<template #slot-export>
				<el-button type="primary" size="mini" class="export" @click="exportBtn">
					<i class="el-icon-download"></i>导出
				</el-button>
			</template>
			<template #slot-filter>
				<div class="filter-bar">
					<el-select
						v-model="selects.status"
						size="mini"
						placeholder="请选择任务状态"
						@change="onTaskStatusChange"
					>
						<el-option label="全部" value></el-option>
						<el-option
							:label="item.label"
							:value="item.value"
							v-for="(item, index) in options.status"
							:key="index"
						></el-option>
					</el-select>
					<el-select
						v-model="selects.schedule"
						size="mini"
						placeholder="请选择任务类型"
						@change="onTaskTypeChange"
					>
						<el-option label="全部" value></el-option>
						<el-option label="立即执行" value="2"></el-option>
						<el-option label="定时任务" value="1"></el-option>
					</el-select>
					<el-select
						v-model="selects.userId"
						size="mini"
						placeholder="请选择运营人"
						@change="onStaffChange"
						filterable
					>
						<el-option label="全部" value></el-option>
						<el-option
							:label="item.username"
							:value="item.id"
							v-for="(item, index) in options.staff"
							:key="index"
						></el-option>
					</el-select>
					<date-picker
						style="width:350px;margin-left: 20px"
						:datas="datas"
						@change="val => refresh({ startTime: val[0], endTime: val[1], page: 1 })"
						@refresh="refresh({ startTime: '', endTime: '', page: 1 })"
					></date-picker>
				</div>
			</template>

			<template #table-column-info="{scope}">
				<div class="info">
					<p>
						标题：
						<span>{{ scope.row.title }}</span>
					</p>
					<p>
						总数：
						<span>{{ scope.row.totalNum }}</span>
					</p>
					<p>
						领取次数：
						<span>{{ scope.row.userTotal }}</span>
					</p>
					<p>
						单个金额：
						<span>￥{{ scope.row.perface }}元</span>
					</p>
					<p>
						创建类型：
						<span>{{ scope.row.type | typeFilter }}</span>
					</p>
					<p>
						开始时间：
						<span>{{ scope.row.startTime }}</span>
					</p>
					<p>
						结束时间：
						<span>{{ scope.row.endTime }}</span>
					</p>
				</div>
			</template>

			<template #table-column-goodsInfo="{scope}">
				<div class="goodsInfo-box">
					<div class="info">
						<div class="info-box" v-if="scope.row.productPicUrl">
							<img
								:src="scope.row.productPicUrl"
								alt
								class="goodsInfo-img"
								v-if="scope.row.productPicUrl"
							/>
							<div class="title-box">
								<div class="name">
									<a
										:href="scope.row.productItemUrl"
										target="_blank"
										class="titel"
										v-if="scope.row.productTitle"
										:title="scope.row.productTitle"
										>{{ scope.row.productTitle }}</a
									>
									<i
										class="el-icon-copy-document"
										v-copy="scope.row.productTitle"
										title="复制商品名称"
									></i>
								</div>

								<p class="shop" v-if="scope.row.productShopName">
									{{ scope.row.productShopName }}
								</p>
							</div>
						</div>
						<p>
							商品ID：{{ scope.row.itemId }}
							<i
								class="el-icon-copy-document"
								v-copy="scope.row.itemId"
								title="复制商品ID"
							></i>
						</p>
						<p>
							优惠券ID：{{ scope.row.activity }}
							<i
								class="el-icon-copy-document"
								v-copy="scope.row.activity"
								title="复制优惠券ID"
							></i>
						</p>
					</div>
				</div>
			</template>

			<template #table-column-taskTime="{scope}">
				<div class="info">
					<p>定时时间：{{ scope.row.scheduleTime || '未设置' }}</p>
					<p>执行时间：{{ scope.row.updateTime }}</p>
				</div>
			</template>

			<template #table-column-tkl="{scope}">
				<div class="info">
					<p>
						{{ scope.row.tkl || '无' }}
						<i
							class="el-icon-copy-document"
							v-copy="scope.row.tkl"
							v-if="scope.row.tkl"
							title="复制淘口令"
						></i>
					</p>
				</div>
			</template>

			<template #table-column-status="{scope}">
				<el-tag size="small" v-if="scope.row.status === 0">待执行</el-tag>
				<el-tag type="success" size="small" v-else-if="scope.row.status === 1">成功</el-tag>
				<el-tooltip
					:content="scope.row.error || '暂无原因'"
					v-else-if="scope.row.status === 2"
					placement="top"
				>
					<el-tag type="info" size="small">失败</el-tag>
				</el-tooltip>
			</template>

			<template #slot-row-detail="{scope}">
				<div class="record-detail" v-if="scope.row.rightsId">
					<span @click="recordDetail(scope.row)">查看领取明细</span>
				</div>
			</template>

			<template #slot-row-copy="{scope}">
				<div class="copy">
					<el-tooltip :content="scope.row.tkl" placement="top">
						<el-button
							v-copy="scope.row.tkl"
							type="text"
							size="small"
							v-if="scope.row.tkl"
							>复制淘口令</el-button
						>
					</el-tooltip>
				</div>
			</template>
			<!-- <template #slot-info="{scope}">
				<goods-info></goods-info>
			</template>-->
		</cl-crud>
		<detail-dig ref="detail"></detail-dig>
	</div>
</template>

<script>
import moment from 'moment';
import { Type_TLJ, Task_Status } from '@/dict/index';
import { mapMutations } from 'vuex';
import { download } from '@/utils/index';
import DetailDig from './components/detail-dig';
import DatePicker from '@/components/order/date-picker';
import GoodsInfo from './components/goods-info';

export default {
	data() {
		return {
			crud: null,
			options: {
				account: [],
				status: [],
				staff: [],
				userList: []
			},
			selects: {},
			datas: [moment().format('YYYY-MM-DD 00:00:00'), moment().format('YYYY-MM-DD 23:59:59')]
		};
	},
	components: {
		'detail-dig': DetailDig,
		DatePicker
		// GoodsInfo
	},

	created() {
		this.options.status = Task_Status;
		this.getStaffList();
	},

	computed: {},

	methods: {
		...mapMutations(['SET_RECORDOBJ']),
		onLoad({ ctx, app }) {
			this.crud = app;
			let that = this;

			ctx.service(this.$service.coupon.record)
				.set('dict', {
					search: {
						query: 'status'
					}
				})
				.set('upsert', {
					props: {
						width: '700px',
						labelWidth: '150px'
					},
					items: [
						{
							component: {
								name: 'base-info',

								render() {
									return (
										<p style="margin-left: -120px;border-left:5px solid #FF4400;line-height: 16px;padding-left: 8px;">
											基础信息
										</p>
									);
								}
							}
						},
						{
							prop: 'userIds',
							label: '运营人',
							span: 13,
							value: [],
							component: {
								name: 'el-select',
								options: [],
								props: {
									clearable: true,
									multiple: true,
									filterable: true
								},
								attrs: {
									placeholder: '请选择运营人'
								}
							},
							rules: {
								required: true,
								message: '运营人不能为空'
							}
						},
						{
							span: 1,
							component: {
								name: 'add-staff',

								methods: {
									async addStaff() {
										let staffList = await this.$service.account.extension.staffList();
										staffList = staffList.map(e => {
											return {
												label: e.username,
												value: e.id
											};
										});
										this.$refs['cl-form'].open({
											props: {
												title: '绑定APP账号',
												width: '550px',
												showClose: false,
												'label-width': '120px'
											},
											items: [
												{
													prop: 'appKey',
													label: 'AppKey',
													component: {
														name: 'el-input',
														props: {
															clearable: true
														},
														attrs: {
															placeholder: '请输入AppKey'
														}
													},
													rules: {
														required: true,
														message: 'AppKey不能为空'
													}
												},
												{
													prop: 'appSecret',
													label: 'AppSecret',
													component: {
														name: 'el-input',
														props: {
															clearable: true
														},
														attrs: {
															placeholder: '请输入AppSecret'
														}
													},
													rules: {
														required: true,
														message: 'AppSecret不能为空'
													}
												},
												{
													prop: 'adzoneId',
													label: '阿里妈妈广告位',
													component: {
														name: 'el-input',
														props: {
															clearable: true
														},
														attrs: {
															placeholder:
																'请输入App对应的阿里妈妈广告位'
														}
													},
													rules: [
														{
															required: true,
															message:
																'输入的必须是App对应的阿里妈妈广告位'
														},
														{
															validator: (rules, value, callback) => {
																let reg = /^[0-9]*$/;
																if (!reg.test(value)) {
																	callback(
																		new Error(
																			'请输入正确的阿里妈妈广告位'
																		)
																	);
																} else {
																	callback();
																}
															}
														}
													]
												},
												{
													prop: 'userIds',
													label: '运营人',
													value: [],
													component: {
														name: 'el-select',
														options: staffList,
														props: {
															clearable: true,
															multiple: true,
															filterable: true
														},
														attrs: {
															placeholder: '请选择运营人'
														}
													},
													rules: {
														required: true,
														message: '运营人不能为空'
													}
												}
											],
											on: {
												submit: ({ data, done, close }) => {
													this.$service.coupon.account
														.add({
															...data,
															userIds: data.userIds.join(',')
														})
														.then(() => {
															this.$message.success('新增成功');
															this.$service.coupon.account
																.userList()
																.then(res => {
																	let staff = res.map(e => {
																		return {
																			label: e.username,
																			value: e.userId
																		};
																	});
																	app.setData(
																		'upsert.items[prop:userIds].component.options',
																		staff
																	);
																	let idArr = app.getData(
																		'upsert.form.userIds'
																	);
																	app.setForm(
																		'userIds',
																		idArr.concat(data.userIds)
																	);
																	close();
																})
																.catch(err => {
																	this.$message.error(err);
																	done();
																});
														});
												}
											}
										});
									}
								},

								render() {
									return (
										<div>
											<el-tooltip
												effect="dark"
												content="添加App账号"
												placement="top">
												<i
													class="el-icon-plus"
													style="margin-left: -140px;cursor: pointer; color: #FF4400;"
													on-click={this.addStaff}></i>
											</el-tooltip>
											<cl-form ref="cl-form"></cl-form>
										</div>
									);
								}
							}
						},
						{
							prop: 'type',
							label: '创建类型',
							span: 10,
							value: this.$store.getters.recordObj.type,
							component: {
								name: 'el-select',
								attrs: {
									placeholder: '请选择'
								},
								props: {
									clearable: true
								},
								options: Type_TLJ
							},
							rules: {
								required: true,
								message: '创建类型不能为空'
							}
						},
						{
							prop: 'itemId',
							label: '商品链接',
							span: 21,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '示例：https://detail.tmall.com/item.htm?id=xxxxx',
									clearable: true
								}
								// on: {
								// 	blur: () => {
								// 		let goodUrl = app.getData('upsert.form.itemId');
								// 		console.log('goodUrl', goodUrl);
								// 		if (!goodUrl) return false;
								// 		this.$service.coupon.record
								// 			.goodsInfo({
								// 				product_url: goodUrl
								// 			})
								// 			.then(res => {
								// 				console.log('goodsInfo', res);
								// 				app.setData('upsert.form.goodsInfo', res);
								// 				if (res.productTitle) {
								// 					app.setData(
								// 						'upsert.items[prop:goodsInfo].hidden',
								// 						false
								// 					);
								// 				} else {
								// 					app.setData(
								// 						'upsert.items[prop:goodsInfo].hidden',
								// 						true
								// 					);
								// 				}
								// 			});
								// 	}
								// }
							},
							rules: [
								{
									required: true,
									message: '请输入商品链接'
								},
								{
									validator: (rules, value, callback) => {
										let reg = new RegExp(/id=/);
										if (!reg.test(value)) {
											callback(
												new Error(
													'示例：https://detail.tmall.com/item.htm?id=xxxxx'
												)
											);
										} else {
											callback();
										}
									}
								}
							]
						},
						{
							span: 2,
							component: {
								name: 'setting',
								methods: {
									checkGoods() {
										let goodUrl = app.getData('upsert.form.itemId');
										console.log('goodUrl', goodUrl);
										if (!goodUrl) return false;
										this.$service.coupon.record
											.goodsInfo({
												product_url: goodUrl
											})
											.then(res => {
												console.log('goodsInfo', res);
												app.setData('upsert.form.goodsInfo', res);
												if (res.productTitle) {
													app.setData(
														'upsert.items[prop:goodsInfo].hidden',
														false
													);
												} else {
													app.setData(
														'upsert.items[prop:goodsInfo].hidden',
														true
													);
												}
											})
											.catch(err => {
												that.$message.error(err);
											});
									}
								},
								render() {
									return (
										<div style="margin-left:-124px">
											<el-button
												style=""
												type="primary"
												size="small"
												on-click={this.checkGoods}>
												检索
											</el-button>
										</div>
									);
								}
							}
						},
						{
							hidden: true,
							prop: 'goodsInfo',
							label: '商品信息',
							component: GoodsInfo
						},
						{
							prop: 'activity',
							label: '优惠券链接',
							component: {
								name: 'el-input',
								attrs: {
									placeholder:
										'示例：https://uland.taobao.com/quan/detail?sellerId=xxxxx&activityId=xxxxx',
									clearable: true
								}
							},
							rules: [
								{
									required: false
									// message: '请输入优惠券链接'
								},
								{
									validator: (rules, value, callback) => {
										let reg = new RegExp(/activityId=/);
										if (value && !reg.test(value)) {
											callback(
												new Error(
													'示例：https://uland.taobao.com/quan/detail?sellerId=xxxxx&activityId=xxxxx'
												)
											);
										} else {
											callback();
										}
									}
								}
							]
						},
						{
							prop: 'title',
							label: '淘礼金名称',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入名称',
									clearable: true,
									maxlength: 10
								}
							},
							rules: [
								{
									required: true,
									message: '淘礼金名字不能为空'
								},
								{
									min: 5,
									max: 10,
									message: '淘礼金名字在5 ~ 10个字符之间'
								}
							]
						},
						{
							prop: 'totalNum',
							label: '淘礼金个数',
							value: this.$store.getters.recordObj.totalNum,
							component: {
								name: 'el-input-number',
								props: {
									min: 0
								}
							},
							rules: {
								required: true,
								message: '总金额不能为空'
							}
						},
						{
							prop: 'userTotal',
							label: '单用户最多领多少次',
							value: this.$store.getters.recordObj.userTotal,
							component: {
								name: 'el-input-number',
								props: {
									min: 0
								}
							},
							rules: {
								required: true,
								message: '最多领取数量不能为空'
							}
						},
						{
							prop: 'perface',
							label: '单个淘礼金金额',
							value: this.$store.getters.recordObj.perface,
							component: {
								name: 'el-input-number',
								props: {
									min: 0
								}
							},
							rules: {
								required: true,
								message: '单金额不能为空'
							}
						},
						{
							prop: 'startTime',
							label: '开始时间',
							span: 14,
							value: moment().format('YYYY-MM-DD HH:mm:ss'),
							component: {
								name: 'el-date-picker',
								props: {
									type: 'datetime',
									'value-format': 'yyyy-MM-dd HH:mm:ss'
								}
							},
							rules: [
								{
									required: true,
									message: '开始时间不能为空',
									trigger: 'blur'
								}
								// {
								// 	validator: (rules, value, callback) => {
								// 		const h = app.getData('upsert.form.hour') || 0;
								//
								// 		if (
								// 			moment(value)
								// 				.add(h, 'hour')
								// 				.isBefore(moment())
								// 		) {
								// 			callback(new Error('开始时间不能小于当前时间'));
								// 		} else {
								// 			callback();
								// 		}
								// 	}
								// }
							]
						},
						{
							prop: 'hour',
							label: '持续时间（h）',
							span: 10,
							value: 24,
							component: {
								name: 'el-input-number',
								props: {
									min: 0
								}
							},
							rules: {
								required: true,
								message: '持续时间不能为空',
								trigger: 'blur'
							}
						},
						{
							prop: 'scheduleTime',
							label: '定时时间',
							component: {
								name: 'el-date-picker',
								props: {
									type: 'datetime',
									'value-format': 'yyyy-MM-dd HH:mm:ss'
								}
							},
							rules: [
								{
									required: false,
									message: '定时时间不能为空'
								}
								// {
								// 	validator: (rules, value, callback) => {
								// 		if (moment(value).isBefore(moment())) {
								// 			callback(new Error('定时时间不能小于当前时间'));
								// 		} else {
								// 			callback();
								// 		}
								// 	}
								// }
							]
						}
					]
				})
				.set('table', {
					columns: [
						{
							type: 'index',
							label: '序号',
							align: 'center',
							width: '60'
						},
						{
							label: '创建时间',
							prop: 'createTime',
							align: 'center',
							'min-width': 160,
							sortable: true
						},
						{
							label: '信息',
							prop: 'info',
							align: 'left',
							'min-width': 200
						},
						{
							label: '商品信息',
							prop: 'goodsInfo',
							align: 'left',
							'min-width': 180
						},
						{
							label: '任务时间',
							prop: 'taskTime',
							align: 'center',
							'min-width': 200
						},
						{
							label: '淘口令',
							prop: 'tkl',
							align: 'center',
							'min-width': 130
						},
						{
							label: '运营人',
							prop: 'username',
							align: 'center',
							'min-width': 100
						},
						{
							label: '状态',
							prop: 'status',
							align: 'center',
							'min-width': 80,
							fixed: 'right'
						}
					],
					props: {
						'default-sort': {
							order: 'descending',
							prop: 'createTime'
						}
					},
					op: {
						layout: ['slot-row-detail', 'slot-row-copy', 'delete']
					}
				})
				.set('layout', [
					[
						'refresh-btn',
						'slot-add',
						'slot-filter',
						'flex1',
						'slot-export',
						'search-key'
					],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('open', async () => {
					app.setData('upsert.items[prop:goodsInfo].hidden', true);
					app.setData(
						'upsert.items[prop:userIds].component.options',
						this.options.userList.map(e => {
							return {
								label: e.username,
								value: e.userId
							};
						})
					);
					app.setForm('userIds', this.$store.getters.recordObj.userIds);
					app.setForm('type', this.$store.getters.recordObj.type);
					app.setForm('startTime', this.$store.getters.recordObj.startTime);
					// app.setForm('startTime', moment().format('YYYY-MM-DD HH:mm:ss'));
					app.setForm('hour', this.$store.getters.recordObj.hour);
					app.setForm('totalNum', this.$store.getters.recordObj.totalNum);
					app.setForm('userTotal', this.$store.getters.recordObj.userTotal);
					app.setForm('perface', this.$store.getters.recordObj.perface);
					app.setForm('scheduleTime', this.$store.getters.recordObj.scheduleTime);
					app.setForm('itemId', this.$store.getters.recordObj.itemId);
					app.setForm('activity', this.$store.getters.recordObj.activity);
					app.setForm('title', this.$store.getters.recordObj.title);
				})
				.on('submit', (isEdit, data, { next }) => {
					this.SET_RECORDOBJ({
						...data
					});
					next({
						...data,
						userIds: data.userIds.join(','),
						endTime: moment(data.startTime)
							.add(data.hour, 'hour')
							.format('YYYY-MM-DD HH:mm:ss'),
						...app.getData('upsert.form.goodsInfo')
					});
				})
				.done();

			app.refresh({
				startTime: moment().format('YYYY-MM-DD 00:00:00'),
				endTime: moment().format('YYYY-MM-DD 23:59:59')
			});
		},

		refresh(params) {
			this.datas = [params.startTime, params.endTime];
			this.crud.refresh({
				startTime: moment().format('YYYY-MM-DD 00:00:00'),
				endTime: moment().format('YYYY-MM-DD 23:59:59'),
				...params
			});
		},

		onTaskTypeChange(val) {
			this.refresh({
				schedule: val
			});

			// this.crud.setData('table.columns[prop:updateTime].hidden', val == 2);
			// this.crud.setData('table.columns[prop:scheduleTime].hidden', val == 2);
		},
		onTaskStatusChange(val) {
			this.refresh({
				status: val
			});
		},
		onStaffChange(val) {
			this.refresh({
				userId: val
			});
		},
		exportBtn() {
			let list = this.crud.getData('table.data');
			if (list.length === 0) {
				this.$message.error('当前导出暂无数据');
				return false;
			}
			let schedule = this.selects.schedule;
			if (schedule === undefined) {
				schedule = '';
			}
			let keyWord = this.crud.getData('params').keyWord;
			let status = this.selects.status;
			if (status === undefined) {
				status = '';
			}
			if (keyWord === undefined) {
				keyWord = '';
			}
			console.log(this.datas);
			let startTime = this.datas[0] || null;
			let endTime = this.datas[1] || null;
			this.$service.coupon.record
				.export({
					keyWord,
					schedule,
					status,
					startTime,
					endTime
				})
				.then(res => {
					download({
						data: res,
						fileName: `礼金记录-${moment().format('YYYY-MM-DD HH:mm:ss')}`
					});
				});
		},
		addRecord() {
			this.crud.add();
		},
		recordDetail(item) {
			this.$refs.detail.open(item);
		},
		getStaffList() {
			this.$service.account.extension.staffList().then(res => {
				this.options.staff = res;
			});
			this.$service.coupon.account.userList().then(res => {
				this.options.userList = res;
			});
		}
	},
	filters: {
		// 解析创建类型
		typeFilter(val) {
			let arr = Type_TLJ;
			let label = '';
			for (let i = 0; i < arr.length; i++) {
				if (arr[i].value === val) {
					label = arr[i].label;
				}
			}
			return label;
		}
	}
};
</script>

<style lang="stylus" scoped>
.goodsInfo-box {
	display: flex;
	align-items: center;
	width: 100%;

	img {
		width: 50px;
		height: 50px;
		/* border-radius: 50%; */
		flex-shrink: 0;
	}

	.info {
		width: 100%;
	}

	.info-box {
		margin: 10px 0;
		display: flex;
		align-items: center;

		.img-box {
			width: 500px;
			height: 500px;

			img {
				max-height: 100%;
				max-width: 100%;
			}
		}

		.title-box {
			flex: 1;
			height: 50px;
			margin-left: 10px;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			overflow-x: hidden;

			.name {
				display: flex;
				align-items: center;

				a {
					font-size: 12px;
					width: 90%;
					color: $main-color;
					cursor: pointer;
					textOverflow(1);
				}
			}

			.shop {
			}
		}
	}
}

.info {
	span {
		color: $main-color;
	}

	i {
		color: $main-color;
		cursor: pointer;
		font-size: 14px;
	}
}

.export {
	margin-right: 10px;
}

.record-detail {
	display: flex;
	justify-content: center;
	align-items: center;

	span {
		background: $main-color;
		border-radius: 50px;
		cursor: pointer;
		display: block;
		padding: 4px 14px;
		color: #ffffff;
		transition: 0.3s;

		&:hover {
			opacity: 0.8;
		}
	}
}

>>>.el-dialog {
	.el-form {
		.el-col {
			.el-col-8 {
				.el-form-item__label {
					width: 120px !important;
				}
			}
		}
	}
}

>>>.el-select {
	margin-left: 10px;
}
</style>
